/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-01-30 22:27:18
 */

import { ChatRecord, HistorySession } from '@/interface'
import * as IndexedDB from '@/indexedDB'
import { isNil, equals, last, clone } from 'ramda'
// 获取聊天记录并写入indexedDB数据库
export async function getChatCommunication(friend: HistorySession) {
	const userId = localStorage.getItem('userId') as string
	const historicalUserSessionsId = friend.historicalUserSessionsId
	const parmas: API.blog.chatRecord.getUserChatRecord.Params = {
		userId: Number(userId),
		to_userId: historicalUserSessionsId,
		pageSize: 20,
		group_id: undefined,
	}
	if (!isNil(friend.chatUserGroup)) {
		parmas.to_userId = undefined
		parmas.group_id = historicalUserSessionsId
	}
	const { success, data } = await API.blog.chatRecord.getUserChatRecord.request(parmas)
	if (success) {
		// 获取聊天记录并比对indexedDB数据库聊天记录是否最新数据
		const userChatRecordReadAll = (await IndexedDB.readAll(
			`user-chat-record-${historicalUserSessionsId}`
		)) as ChatRecord[]
		// bug
		if (!equals(last(userChatRecordReadAll)?.id, friend.latestNews?.id)) {
			IndexedDB.clearTable(`user-chat-record-${friend?.historicalUserSessionsId}`)
			data.data.forEach((chatRecord: ChatRecord) => {
				IndexedDB.add<ChatRecord>(`user-chat-record-${friend?.historicalUserSessionsId}`, clone(chatRecord))
			})
		}
	}
}
